<template>
    <div class="amap-component">
        <!-- 地图容器 -->
        <div ref="mapContainer" class="amap-container" :style="{ width: width, height: height }"></div>

        <!-- 加载状态 -->
        <!-- <div v-if="isLoading" class="amap-loading">
            <div class="loading-spinner"></div>
            <span>地图加载中...</span>
        </div> -->

        <!-- 错误提示 -->
        <!-- <div v-if="error" class="amap-error">
            <span>{{ error }}</span>
            <button @click="retryInit" class="retry-btn">重试</button>
        </div> -->

        <!-- 控制面板 -->
        <div v-if="showControls && mapState.isReady" class="amap-controls">
            <!-- 区域搜索 -->
            <div class="control-section">
                <h4>区域搜索</h4>
                <div class="control-item">
                    <input v-model="searchKeyword" @keyup.enter="searchDistrict" placeholder="输入省市区名称"
                        class="search-input" />
                    <button @click="searchDistrict" class="btn">搜索</button>
                </div>

                <div class="control-item">
                    <label>显示级别:</label>
                    <select v-model="selectedLevel" @change="changeLevel" class="level-select">
                        <option value="province">省级</option>
                        <option value="city">市级</option>
                        <option value="district">区县级</option>
                    </select>
                </div>

                <div class="control-item" v-if="canGoBack">
                    <button @click="goBack" class="btn btn-secondary">
                        返回上一级
                    </button>
                </div>
            </div>

            <!-- 掩膜控制 -->
            <div class="control-section">
                <h4>掩膜控制</h4>
                <div class="control-item">
                    <label>
                        <input type="checkbox" :checked="maskEnabled" @change="toggleMask" />
                        启用掩膜效果
                    </label>
                </div>

                <div v-if="maskEnabled" class="mask-controls">
                    <div class="control-item">
                        <label>选中区域透明度:</label>
                        <input type="range" min="0" max="1" step="0.1" :value="selectedOpacity"
                            @input="updateSelectedOpacity" />
                        <span>{{ selectedOpacity }}</span>
                    </div>

                    <div class="control-item">
                        <label>掩膜区域透明度:</label>
                        <input type="range" min="0" max="1" step="0.1" :value="maskOpacity"
                            @input="updateMaskOpacity" />
                        <span>{{ maskOpacity }}</span>
                    </div>

                    <div class="control-item">
                        <label>选中区域颜色:</label>
                        <input type="color" :value="selectedColor" @input="updateSelectedColor" />
                    </div>

                    <div class="control-item">
                        <label>掩膜区域颜色:</label>
                        <input type="color" :value="maskColor" @input="updateMaskColor" />
                    </div>

                    <div class="control-item">
                        <button @click="clearAllMask" class="btn btn-warning">
                            清除掩膜
                        </button>
                    </div>
                </div>
            </div>

            <!-- 道路控制 -->
            <div class="control-section">
                <h4>道路控制</h4>
                <div class="control-item">
                    <label>
                        <input type="checkbox" :checked="roadsEnabled" @change="toggleRoads" />
                        显示道路
                    </label>
                </div>

                <div v-if="roadsEnabled" class="road-controls">
                    <div class="control-item">
                        <label>道路类型:</label>
                    </div>

                    <div class="road-types">
                        <div class="control-item">
                            <label>
                                <input type="checkbox" :checked="roadTypes.major"
                                    @change="toggleRoadType('major', $event)" />
                                主干道
                            </label>
                        </div>

                        <div class="control-item">
                            <label>
                                <input type="checkbox" :checked="roadTypes.minor"
                                    @change="toggleRoadType('minor', $event)" />
                                次要道路
                            </label>
                        </div>

                        <div class="control-item">
                            <label>
                                <input type="checkbox" :checked="roadTypes.highways"
                                    @change="toggleRoadType('highways', $event)" />
                                高速公路
                            </label>
                        </div>

                        <div class="control-item">
                            <label>
                                <input type="checkbox" :checked="roadTypes.subways"
                                    @change="toggleRoadType('subways', $event)" />
                                地铁线路
                            </label>
                        </div>
                    </div>

                    <div class="control-item">
                        <label>道路透明度:</label>
                        <input type="range" min="0" max="1" step="0.1" :value="roadOpacity"
                            @input="updateRoadOpacity" />
                        <span>{{ roadOpacity }}</span>
                    </div>

                    <div class="control-item">
                        <button @click="clearAllRoads" class="btn btn-warning">
                            清除道路
                        </button>
                    </div>
                </div>
            </div>

            <!-- 当前区域信息 -->
            <div v-if="mapState.currentDistrict" class="current-district">
                <h4>当前区域</h4>
                <p><strong>名称:</strong> {{ mapState.currentDistrict.name }}</p>
                <p><strong>代码:</strong> {{ mapState.currentDistrict.adcode }}</p>
                <p><strong>级别:</strong> {{ mapState.currentDistrict.level }}</p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useAMap } from './useAMap'
import type { AMapComponentProps } from './types'

// 组件属性
interface Props {
    // 地图配置
    apiKey: string
    apiVersion?: string

    // 容器样式
    width?: string
    height?: string

    // 地图选项
    center?: [number, number]
    zoom?: number
    mapStyle?: string

    // 功能配置
    showControls?: boolean
    enableMask?: boolean
    showRoads?: boolean

    // 初始搜索区域
    initialDistrict?: string

    // 样式配置
    selectedStyle?: any
    unselectedStyle?: any
    roadStyle?: any
}

const props = withDefaults(defineProps<Props>(), {
    apiVersion: '2.0',
    width: '100%',
    height: '500px',
    center: () => [116.397428, 39.90923], // 北京
    zoom: 10,
    mapStyle: 'amap://styles/normal',
    showControls: true,
    enableMask: true,
    showRoads: true
})

// 事件定义
const emit = defineEmits<{
    'district-click': [district: any]
    'map-ready': [map: any]
    'district-change': [district: any]
}>()

// 响应式数据
const searchKeyword = ref('')
const maskEnabled = ref(props.enableMask)
const roadsEnabled = ref(props.showRoads)

// 掩膜样式控制
const selectedOpacity = ref(0.4)
const maskOpacity = ref(0.2)
const selectedColor = ref('#0078ff')
const maskColor = ref('#f0f0f0')

// 道路控制
const roadTypes = ref({
    major: true,
    minor: false,
    highways: true,
    subways: false
})
const roadOpacity = ref(0.8)

// 区域切换和交互
const selectedLevel = ref('province')
const canGoBack = ref(false)
const levelHistory = ref([])

// 使用地图Hook
const {
    mapContainer,
    isLoading,
    error,
    mapState,
    currentConfig,
    initMap,
    searchAndShowDistrict,
    clearDistrictPolygons,
    updateMaskConfig,
    updateRoadConfig,
    setMaskEnabled,
    updateSelectedStyle,
    updateMaskStyle,
    clearMask,
    setRoadEnabled,
    showRoadsInDistrict,
    updateRoadStyle,
    setRoadTypeVisible,
    clearRoads,
    showProvinceDistricts,
    showCityDistricts,
    showDistrictDistricts,
    goBackToPreviousLevel,
    getCurrentLevel
} = useAMap({
    mapConfig: {
        key: props.apiKey,
        version: props.apiVersion,
        plugins: ['AMap.DistrictSearch', 'AMap.Polygon']
    },
    mapOptions: {
        center: props.center,
        zoom: props.zoom,
        mapStyle: props.mapStyle
    },
    districtConfig: {
        level: 'province',
        keyword: '',
        subdistrict: 1,
        extensions: 'all'
    },
    maskConfig: {
        enableMask: props.enableMask,
        selectedStyle: props.selectedStyle || {
            strokeColor: '#0078ff',
            strokeWeight: 3,
            strokeOpacity: 1,
            fillColor: '#0078ff',
            fillOpacity: 0.4
        },
        unselectedStyle: props.unselectedStyle || {
            strokeColor: '#cccccc',
            strokeWeight: 1,
            strokeOpacity: 0.8,
            fillColor: '#f0f0f0',
            fillOpacity: 0.2
        }
    },
    roadConfig: {
        showRoads: props.showRoads,
        roadStyle: props.roadStyle || {
            strokeColor: '#666666',
            strokeWeight: 2,
            strokeOpacity: 0.8
        }
    },
    autoInit: true
})

// 搜索区域
const searchDistrict = async () => {
    if (!searchKeyword.value.trim()) return

    try {
        // 根据当前级别搜索对应的区域
        if (selectedLevel.value === 'province') {
            await showProvinceDistricts(searchKeyword.value)
        } else if (selectedLevel.value === 'city') {
            await showCityDistricts(searchKeyword.value)
        } else {
            await showDistrictDistricts(searchKeyword.value)
        }

        emit('district-search', {
            keyword: searchKeyword.value,
            level: selectedLevel.value
        })
    } catch (error) {
        console.error('搜索区域失败:', error)
        emit('error', { type: 'search', message: '搜索区域失败' })
    }
}

// 切换显示级别
const changeLevel = async () => {
    try {
        if (selectedLevel.value === 'province') {
            await showProvinceDistricts()
            canGoBack.value = false
        } else if (selectedLevel.value === 'city') {
            await showCityDistricts()
        } else {
            await showDistrictDistricts()
        }

        emit('level-change', selectedLevel.value)
    } catch (error) {
        console.error('切换级别失败:', error)
        emit('error', { type: 'level-change', message: '切换级别失败' })
    }
}

// 返回上一级
const goBack = async () => {
    try {
        const result = await goBackToPreviousLevel()
        if (result) {
            selectedLevel.value = getCurrentLevel()
            canGoBack.value = selectedLevel.value !== 'province'
            emit('level-back', selectedLevel.value)
        }
    } catch (error) {
        console.error('返回上一级失败:', error)
        emit('error', { type: 'go-back', message: '返回上一级失败' })
    }
}

// 搜索处理
const handleSearch = async () => {
    if (!searchKeyword.value.trim()) return

    await searchAndShowDistrict(searchKeyword.value.trim())

    if (mapState.currentDistrict) {
        emit('district-change', mapState.currentDistrict)
    }
}

// 切换掩膜
const toggleMask = () => {
    updateMaskConfig({ enableMask: maskEnabled.value })
}

// 更新选中区域透明度
const updateSelectedOpacity = (event: Event) => {
    const target = event.target as HTMLInputElement
    selectedOpacity.value = parseFloat(target.value)
    updateMaskConfig({
        selectedStyle: {
            ...currentConfig.maskConfig.selectedStyle,
            fillOpacity: selectedOpacity.value
        }
    })
}

// 更新掩膜区域透明度
const updateMaskOpacity = (event: Event) => {
    const target = event.target as HTMLInputElement
    maskOpacity.value = parseFloat(target.value)
    updateMaskConfig({
        unselectedStyle: {
            ...currentConfig.maskConfig.unselectedStyle,
            fillOpacity: maskOpacity.value
        }
    })
}

// 更新选中区域颜色
const updateSelectedColor = (event: Event) => {
    const target = event.target as HTMLInputElement
    selectedColor.value = target.value
    updateMaskConfig({
        selectedStyle: {
            ...currentConfig.maskConfig.selectedStyle,
            fillColor: selectedColor.value
        }
    })
}

// 更新掩膜区域颜色
const updateMaskColor = (event: Event) => {
    const target = event.target as HTMLInputElement
    maskColor.value = target.value
    updateMaskConfig({
        unselectedStyle: {
            ...currentConfig.maskConfig.unselectedStyle,
            fillColor: maskColor.value
        }
    })
}

// 清除所有掩膜
const clearAllMask = () => {
    clearDistrictPolygons()
}

// 切换道路类型显示
const toggleRoadType = (type: string, event: Event) => {
    const target = event.target as HTMLInputElement
    const typeMap = {
        'major': '主干道',
        'minor': '次干道',
        'highways': '高速公路',
        'subways': '地铁'
    }

    roadTypes.value[type] = target.checked
    setRoadTypeVisible(typeMap[type], target.checked)

    // 更新道路配置
    const configKey = {
        'major': 'showMajorRoads',
        'minor': 'showMinorRoads',
        'highways': 'showHighways',
        'subways': 'showSubways'
    }

    updateRoadConfig({
        [configKey[type]]: target.checked
    })
}

// 更新道路透明度
const updateRoadOpacity = (event: Event) => {
    const target = event.target as HTMLInputElement
    roadOpacity.value = parseFloat(target.value)
    updateRoadStyle({ strokeOpacity: roadOpacity.value })
}

// 清除所有道路
const clearAllRoads = () => {
    clearRoads()
}

// 监听地图状态变化
watch(() => mapState.currentDistrict, (newDistrict) => {
    if (newDistrict) {
        canGoBack.value = selectedLevel.value !== 'province'

        // 如果启用了道路显示，自动显示当前区域的道路
        if (roadsEnabled.value) {
            showRoadsInDistrict(newDistrict)
        }
    }
})

// 监听级别变化
watch(() => selectedLevel.value, () => {
    canGoBack.value = selectedLevel.value !== 'province'
})

// 切换道路显示
const toggleRoads = (event: Event) => {
    const target = event.target as HTMLInputElement
    roadsEnabled.value = target.checked
    setRoadEnabled(roadsEnabled.value)

    // 如果启用道路且有当前区域，则显示该区域的道路
    if (roadsEnabled.value && mapState.currentDistrict) {
        showRoadsInDistrict(mapState.currentDistrict)
    }
}

// 重试初始化
const retryInit = async () => {
    await initMap()
}

// 监听地图就绪状态
watch(() => mapState.isReady, (isReady) => {
    if (isReady && mapState.map) {
        emit('map-ready', mapState.map)

        // 如果有初始区域，自动搜索
        if (props.initialDistrict) {
            searchKeyword.value = props.initialDistrict
            searchDistrict()
        }
    }
})

// 监听当前区域变化
watch(() => mapState.currentDistrict, (district) => {
    if (district) {
        emit('district-click', district)
    }
})

// 暴露方法给父组件
defineExpose({
    searchDistrict: searchAndShowDistrict,
    clearDistricts: clearDistrictPolygons,
    getMapInstance: () => mapState.map,
    getCurrentDistrict: () => mapState.currentDistrict
})
</script>

<style scoped>
.amap-component {
    position: relative;
    width: 100%;
    height: 100%;
}

.amap-container {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    overflow: hidden;
}

.amap-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    background: rgba(255, 255, 255, 0.9);
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-spinner {
    width: 32px;
    height: 32px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #0078ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.amap-error {
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: #ff4d4f;
    color: white;
    padding: 12px 16px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.retry-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
}

.retry-btn:hover {
    background: rgba(255, 255, 255, 0.3);
}

.amap-controls {
    position: absolute;
    top: 20px;
    right: 20px;
    background: white;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    min-width: 280px;
    max-height: calc(100% - 40px);
    overflow-y: auto;
    z-index: 1000;
}

.control-group {
    margin-bottom: 16px;
}

.control-group:last-child {
    margin-bottom: 0;
}

.control-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
}

.search-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    margin-bottom: 8px;
    font-size: 14px;
}

.search-input:focus {
    outline: none;
    border-color: #0078ff;
    box-shadow: 0 0 0 2px rgba(0, 120, 255, 0.2);
}

.search-btn {
    width: 100%;
    padding: 8px 16px;
    background: #0078ff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.2s;
}

.search-btn:hover {
    background: #0056cc;
}

.search-btn:active {
    background: #004499;
}

.current-district {
    background: #f8f9fa;
    padding: 12px;
    border-radius: 6px;
    border-left: 4px solid #0078ff;
}

.current-district h4 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 14px;
}

.current-district p {
    margin: 4px 0;
    font-size: 12px;
    color: #666;
}

.current-district strong {
    color: #333;
}

.control-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
}

.control-section h4 {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 14px;
    font-weight: 600;
}

.control-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.control-item:last-child {
    margin-bottom: 0;
}

.control-item label {
    font-size: 12px;
    color: #666;
    min-width: 80px;
}

.control-item input[type="range"] {
    flex: 1;
    min-width: 80px;
}

.control-item input[type="color"] {
    width: 40px;
    height: 24px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.control-item span {
    font-size: 12px;
    color: #333;
    min-width: 30px;
    text-align: center;
}

.mask-controls {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #e0e0e0;
}

.road-controls {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #e0e0e0;
}

.road-types {
    margin: 8px 0;
    padding-left: 12px;
}

.road-types .control-item {
    margin-bottom: 6px;
}

.road-types .control-item label {
    font-size: 11px;
    min-width: auto;
}

.level-select {
    padding: 4px 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 12px;
    background: white;
    min-width: 80px;
}

.level-select:focus {
    outline: none;
    border-color: #0078ff;
}

.btn-secondary {
    background-color: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background-color: #5a6268;
}

.btn {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
}

.btn-warning {
    background: #ff9800;
    color: white;
}

.btn-warning:hover {
    background: #f57c00;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .amap-controls {
        position: static;
        width: 100%;
        margin-top: 16px;
        border-radius: 0;
        box-shadow: none;
        border-top: 1px solid #e8e8e8;
    }

    .amap-component {
        flex-direction: column;
    }
}
</style>